package com.roncoo.education.api;

import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageInfo;
import com.roncoo.education.api.request.AdminSystemRequest;
import com.roncoo.education.db.entity.AdminSystem;
import com.roncoo.education.db.service.AdminSystemService;
import com.roncoo.education.util.MyJwtUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;

@RestController
@RequestMapping("/api/admin")
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class AdminSystemController {

    @Resource
    private AdminSystemService adminService;

    @Resource
    MyJwtUtil myJwtUtil;

    @PostMapping("/login")
    public String login(String username,String password) {
        String token = adminService.login(username, password);
        if (token != null) {
            return token;
        }
        return "登录失败";
    }

    @PostMapping("/logout")
    public String logout(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        Long adminId = myJwtUtil.getUsernameFromToken(token);
        return String.valueOf(adminId);
    }

    @PostMapping("/save")
    public String saveAdmin(@Valid @RequestBody AdminSystemRequest req){
        Map<String,String> ret = adminService.saveAdmin(req);
        return JSONUtil.toJsonStr(ret);
    }
    @GetMapping("/getAdmin")
    public String getAdmin(Long adminId){
        AdminSystem admin = adminService.getAdmin(adminId);
        return JSONUtil.toJsonStr(admin);
    }

    @PostMapping("/adminList")
    public String getAdminList(@Valid @RequestBody AdminSystemRequest req){

        PageInfo<AdminSystem> pageInfo = adminService.getAdminList(req);
        return JSONUtil.toJsonStr(pageInfo);
    }


}
